import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import actionCreators from "../store/actionCreators/user";
function UserList() {
  const users = useSelector((state) => state.user.list);
  const dispatch = useDispatch();
  // 只会在客户端执行，不会在服务端执行
  useEffect(() => {
    if (users.length === 0) {
      dispatch(actionCreators.getUserList());
    }
  }, []);
  console.log(users, "users");
  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

// 当有路由组件在服务器端获取数据的方法
UserList.loadData = (store) => {
  // 等待此pormise完成后仓库就会有数据了，就可以用仓库的数据渲染带真实的数据的HTML，在发给客户端
  return store.dispatch(actionCreators.getUserList());
};

export default UserList;
